package com.dyna.core.aop.aspect;

import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class RequestLimiterAspect {

    // 设置每秒允许的最大请求数为5
    private static final RateLimiter rateLimiter = RateLimiter.create(2.0);

    @Pointcut("@annotation(com.dyna.core.aop.annotation.RequestLimiter)")
    public void requestLimiter() {}

    @Around("requestLimiter()")
    public Object around(ProceedingJoinPoint joinPoint) {
        Object obj = null;
        long requestId = Thread.currentThread().getId();
        try {
            if (rateLimiter.tryAcquire()) {
                log.info("处理请求: " + requestId);
                // 进行实际的请求处理
            } else {
                log.info("请求 " + requestId + " 被限流");
                // 可以返回错误信息或者进行其他操作
            }
            obj = joinPoint.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        return obj;
    }

}
